package com.wlit;

public class CRC16Utils {
    private static final int POLYNOMIAL = 0xA001;
    private static final int INIT_VALUE = 0xFFFF;

    public static int calculate(byte[] data) {
        int crc = INIT_VALUE;
        for (byte b : data) {
            crc ^= (b & 0xFF);
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc = (crc >> 1) ^ POLYNOMIAL;
                } else {
                    crc >>= 1;
                }
            }
        }
        // 反转CRC校验码
        int reversedCrc = (crc & 0xFF) << 8 | (crc >> 8) & 0xFF;
        return reversedCrc;
    }
}